const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const { action } = event

  try {
    switch (action) {
      case 'reverseGeocode':
        return await reverseGeocode(event)
      case 'getWeather':
        return await getWeather(event)
      case 'searchCities':
        return await searchCities(event)
      default:
        throw new Error('未知的操作类型')
    }
  } catch (error) {
    console.error('云函数执行失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 逆地理编码
async function reverseGeocode(event) {
  const { latitude, longitude } = event
  
  try {
    console.log('📍 收到坐标:', { latitude, longitude })
    
    // 默认返回贵阳市观山湖区
    let result = {
      province: '贵州省',
      city: '贵阳市',
      district: '观山湖区',
      street: '数智大厦',
      formatted_address: '贵州省贵阳市观山湖区数智大厦',
      isAccurate: true
    }

    // 根据坐标范围判断具体城市（仅限贵州省）
    if (latitude && longitude) {
      const guizhouCityBounds = [
        // 贵阳市 - 重新调整各区边界，更准确反映真实地理位置
        { 
          name: '贵阳市', 
          bounds: { north: 27.2, south: 26.0, east: 107.5, west: 105.8 },
          districts: [
            // 观山湖区：位于贵阳西北部，包括金阳新区、会展城等
            { name: '观山湖区', bounds: { north: 26.75, south: 26.55, east: 106.75, west: 106.50 } },
            // 南明区：位于贵阳南部，包括花果园、二七路等传统市中心
            { name: '南明区', bounds: { north: 26.65, south: 26.45, east: 106.85, west: 106.65 } },
            // 云岩区：位于贵阳北部，包括大营坡、黔灵山等
            { name: '云岩区', bounds: { north: 26.70, south: 26.55, east: 106.80, west: 106.65 } },
            // 花溪区：位于贵阳南部，包括花溪大学城
            { name: '花溪区', bounds: { north: 26.55, south: 26.30, east: 106.80, west: 106.60 } },
            // 乌当区：位于贵阳东北部
            { name: '乌当区', bounds: { north: 26.80, south: 26.60, east: 107.10, west: 106.80 } },
            // 白云区：位于贵阳北部
            { name: '白云区', bounds: { north: 26.85, south: 26.65, east: 106.80, west: 106.60 } }
          ]
        },
        // 遵义市
        { 
          name: '遵义市', 
          bounds: { north: 29.0, south: 27.0, east: 108.5, west: 105.5 },
          districts: [
            { name: '红花岗区', bounds: { north: 27.8, south: 27.6, east: 107.0, west: 106.8 } },
            { name: '汇川区', bounds: { north: 27.9, south: 27.7, east: 107.1, west: 106.9 } }
          ]
        },
        // 六盘水市
        { 
          name: '六盘水市', 
          bounds: { north: 26.8, south: 25.2, east: 105.2, west: 104.2 },
          districts: [
            { name: '钟山区', bounds: { north: 26.6, south: 26.4, east: 104.9, west: 104.7 } }
          ]
        },
        // 安顺市
        { 
          name: '安顺市', 
          bounds: { north: 26.8, south: 25.2, east: 106.5, west: 105.5 },
          districts: [
            { name: '西秀区', bounds: { north: 26.3, south: 26.1, east: 106.0, west: 105.8 } }
          ]
        },
        // 毕节市
        { 
          name: '毕节市', 
          bounds: { north: 27.8, south: 26.2, east: 106.5, west: 103.8 },
          districts: [
            { name: '七星关区', bounds: { north: 27.4, south: 27.2, east: 105.4, west: 105.2 } },
            { name: '大方县', bounds: { north: 27.2, south: 27.0, east: 105.8, west: 105.6 } },
            { name: '百里杜鹃管理区', bounds: { north: 27.3, south: 27.0, east: 105.8, west: 105.4 } }
          ]
        },
        // 铜仁市
        { 
          name: '铜仁市', 
          bounds: { north: 29.2, south: 27.2, east: 109.8, west: 107.5 },
          districts: [
            { name: '碧江区', bounds: { north: 27.8, south: 27.6, east: 109.2, west: 109.0 } }
          ]
        },
        // 黔东南苗族侗族自治州
        { 
          name: '黔东南苗族侗族自治州', 
          bounds: { north: 27.5, south: 25.5, east: 109.5, west: 107.5 },
          districts: [
            { name: '凯里市', bounds: { north: 26.7, south: 26.5, east: 108.0, west: 107.8 } }
          ]
        },
        // 黔南布依族苗族自治州
        { 
          name: '黔南布依族苗族自治州', 
          bounds: { north: 26.8, south: 24.8, east: 108.5, west: 106.0 },
          districts: [
            { name: '都匀市', bounds: { north: 26.3, south: 26.1, east: 107.6, west: 107.4 } }
          ]
        },
        // 黔西南布依族苗族自治州
        { 
          name: '黔西南布依族苗族自治州', 
          bounds: { north: 26.0, south: 24.5, east: 106.0, west: 104.0 },
          districts: [
            { name: '兴义市', bounds: { north: 25.2, south: 25.0, east: 104.9, west: 104.7 } }
          ]
        },
        // 贵安新区（国家级新区）
        { 
          name: '贵安新区', 
          bounds: { north: 26.5, south: 26.2, east: 106.6, west: 106.2 },
          districts: [
            { name: '贵安新区直管区', bounds: { north: 26.5, south: 26.2, east: 106.6, west: 106.2 } }
          ]
        }
      ]

      // 查找匹配的贵州城市和区县
      for (const city of guizhouCityBounds) {
        const { bounds } = city
        if (latitude >= bounds.south && latitude <= bounds.north && 
            longitude >= bounds.west && longitude <= bounds.east) {
          
          console.log('📍 匹配到城市:', city.name)
          
          // 查找具体的区县（基于坐标的确定性选择）
          let selectedDistrict = city.districts[0].name // 默认第一个区县
          let matchedDistrict = null
          
          for (const district of city.districts) {
            if (district.bounds) {
              const latMatch = latitude >= district.bounds.south && latitude <= district.bounds.north
              const lngMatch = longitude >= district.bounds.west && longitude <= district.bounds.east
              
              console.log(`📍 检查区县 ${district.name}:`, {
                latitude: `${district.bounds.south} <= ${latitude} <= ${district.bounds.north} = ${latMatch}`,
                longitude: `${district.bounds.west} <= ${longitude} <= ${district.bounds.east} = ${lngMatch}`,
                match: latMatch && lngMatch
              })
              
              if (latMatch && lngMatch) {
                selectedDistrict = district.name
                matchedDistrict = district
                console.log('✅ 匹配到区县:', district.name)
                break
              }
            }
          }
          
          if (!matchedDistrict) {
            console.log('⚠️ 未找到精确匹配的区县，使用默认:', selectedDistrict)
          }
          
          result = {
            province: '贵州省',
            city: city.name,
            district: selectedDistrict,
            street: '数智大厦',
            formatted_address: `贵州省${city.name}${selectedDistrict}数智大厦`,
            isAccurate: true
          }
          break
        }
      }
    }

    console.log('📍 最终逆地理编码结果:', result)
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('逆地理编码失败:', error)
    return {
      success: false,
      error: error.message,
      fallbackData: {
        province: '贵州省',
        city: '贵阳市',
        district: '观山湖区',
        street: '数智大厦',
        formatted_address: '贵州省贵阳市观山湖区数智大厦',
        isAccurate: false
      }
    }
  }
}

// 获取天气信息
async function getWeather(event) {
  const { latitude, longitude } = event
  
  try {
    // 模拟贵州地区天气数据
    const guizhouWeatherConditions = [
      { temperature: '22', icon: '☀️', description: '晴朗' },
      { temperature: '18', icon: '⛅', description: '多云' },
      { temperature: '15', icon: '🌧️', description: '小雨' },
      { temperature: '25', icon: '🌤️', description: '晴转多云' },
      { temperature: '20', icon: '☁️', description: '阴天' },
      { temperature: '16', icon: '🌦️', description: '阵雨' },
      { temperature: '23', icon: '🌈', description: '雨后晴' }
    ]
    
    // 随机选择一个天气状态
    const randomWeather = guizhouWeatherConditions[Math.floor(Math.random() * guizhouWeatherConditions.length)]
    
    return {
      success: true,
      data: randomWeather
    }
  } catch (error) {
    console.error('获取天气信息失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 搜索城市（仅限贵州省）
async function searchCities(event) {
  const { keyword } = event
  
  try {
    // 贵州省所有市州和县区的完整列表
    const guizhouCities = [
      // 贵阳市
      { code: '520100', name: '贵阳', province: '贵州省', type: 'city' },
      { code: '520102', name: '南明区', province: '贵州省', type: 'district', parent: '贵阳市' },
      { code: '520103', name: '云岩区', province: '贵州省', type: 'district', parent: '贵阳市' },
      { code: '520111', name: '花溪区', province: '贵州省', type: 'district', parent: '贵阳市' },
      { code: '520112', name: '乌当区', province: '贵州省', type: 'district', parent: '贵阳市' },
      { code: '520113', name: '白云区', province: '贵州省', type: 'district', parent: '贵阳市' },
      { code: '520115', name: '观山湖区', province: '贵州省', type: 'district', parent: '贵阳市' },
      { code: '520121', name: '开阳县', province: '贵州省', type: 'county', parent: '贵阳市' },
      { code: '520122', name: '息烽县', province: '贵州省', type: 'county', parent: '贵阳市' },
      { code: '520123', name: '修文县', province: '贵州省', type: 'county', parent: '贵阳市' },
      { code: '520181', name: '清镇市', province: '贵州省', type: 'city', parent: '贵阳市' },
      
      // 遵义市
      { code: '520300', name: '遵义', province: '贵州省', type: 'city' },
      { code: '520302', name: '红花岗区', province: '贵州省', type: 'district', parent: '遵义市' },
      { code: '520303', name: '汇川区', province: '贵州省', type: 'district', parent: '遵义市' },
      { code: '520304', name: '播州区', province: '贵州省', type: 'district', parent: '遵义市' },
      { code: '520322', name: '桐梓县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520323', name: '绥阳县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520324', name: '正安县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520325', name: '道真县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520326', name: '务川县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520327', name: '凤冈县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520328', name: '湄潭县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520329', name: '余庆县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520330', name: '习水县', province: '贵州省', type: 'county', parent: '遵义市' },
      { code: '520381', name: '赤水市', province: '贵州省', type: 'city', parent: '遵义市' },
      { code: '520382', name: '仁怀市', province: '贵州省', type: 'city', parent: '遵义市' },
      
      // 六盘水市
      { code: '520200', name: '六盘水', province: '贵州省', type: 'city' },
      { code: '520201', name: '钟山区', province: '贵州省', type: 'district', parent: '六盘水市' },
      { code: '520203', name: '六枝特区', province: '贵州省', type: 'district', parent: '六盘水市' },
      { code: '520221', name: '水城区', province: '贵州省', type: 'district', parent: '六盘水市' },
      { code: '520281', name: '盘州市', province: '贵州省', type: 'city', parent: '六盘水市' },
      
      // 安顺市
      { code: '520400', name: '安顺', province: '贵州省', type: 'city' },
      { code: '520402', name: '西秀区', province: '贵州省', type: 'district', parent: '安顺市' },
      { code: '520403', name: '平坝区', province: '贵州省', type: 'district', parent: '安顺市' },
      { code: '520422', name: '普定县', province: '贵州省', type: 'county', parent: '安顺市' },
      { code: '520423', name: '镇宁县', province: '贵州省', type: 'county', parent: '安顺市' },
      { code: '520424', name: '关岭县', province: '贵州省', type: 'county', parent: '安顺市' },
      { code: '520425', name: '紫云县', province: '贵州省', type: 'county', parent: '安顺市' },
      
      // 毕节市
      { code: '520500', name: '毕节', province: '贵州省', type: 'city' },
      { code: '520502', name: '七星关区', province: '贵州省', type: 'district', parent: '毕节市' },
      { code: '520521', name: '大方县', province: '贵州省', type: 'county', parent: '毕节市' },
      { code: '520522', name: '黔西市', province: '贵州省', type: 'city', parent: '毕节市' },
      { code: '520523', name: '金沙县', province: '贵州省', type: 'county', parent: '毕节市' },
      { code: '520524', name: '织金县', province: '贵州省', type: 'county', parent: '毕节市' },
      { code: '520525', name: '纳雍县', province: '贵州省', type: 'county', parent: '毕节市' },
      { code: '520526', name: '威宁县', province: '贵州省', type: 'county', parent: '毕节市' },
      { code: '520527', name: '赫章县', province: '贵州省', type: 'county', parent: '毕节市' },
      { code: '520528', name: '百里杜鹃管理区', province: '贵州省', type: 'management_area', parent: '毕节市' },
      
      // 铜仁市
      { code: '520600', name: '铜仁', province: '贵州省', type: 'city' },
      { code: '520602', name: '碧江区', province: '贵州省', type: 'district', parent: '铜仁市' },
      { code: '520603', name: '万山区', province: '贵州省', type: 'district', parent: '铜仁市' },
      { code: '520621', name: '江口县', province: '贵州省', type: 'county', parent: '铜仁市' },
      { code: '520622', name: '玉屏县', province: '贵州省', type: 'county', parent: '铜仁市' },
      { code: '520623', name: '石阡县', province: '贵州省', type: 'county', parent: '铜仁市' },
      { code: '520624', name: '思南县', province: '贵州省', type: 'county', parent: '铜仁市' },
      { code: '520625', name: '印江县', province: '贵州省', type: 'county', parent: '铜仁市' },
      { code: '520626', name: '德江县', province: '贵州省', type: 'county', parent: '铜仁市' },
      { code: '520627', name: '沿河县', province: '贵州省', type: 'county', parent: '铜仁市' },
      { code: '520628', name: '松桃县', province: '贵州省', type: 'county', parent: '铜仁市' },
      
      // 黔西南州
      { code: '522300', name: '黔西南', province: '贵州省', type: 'prefecture' },
      { code: '522301', name: '兴义市', province: '贵州省', type: 'city', parent: '黔西南州' },
      { code: '522302', name: '兴仁市', province: '贵州省', type: 'city', parent: '黔西南州' },
      { code: '522323', name: '普安县', province: '贵州省', type: 'county', parent: '黔西南州' },
      { code: '522324', name: '晴隆县', province: '贵州省', type: 'county', parent: '黔西南州' },
      { code: '522325', name: '贞丰县', province: '贵州省', type: 'county', parent: '黔西南州' },
      { code: '522326', name: '望谟县', province: '贵州省', type: 'county', parent: '黔西南州' },
      { code: '522327', name: '册亨县', province: '贵州省', type: 'county', parent: '黔西南州' },
      { code: '522328', name: '安龙县', province: '贵州省', type: 'county', parent: '黔西南州' },
      
      // 黔东南州
      { code: '522600', name: '黔东南', province: '贵州省', type: 'prefecture' },
      { code: '522601', name: '凯里市', province: '贵州省', type: 'city', parent: '黔东南州' },
      { code: '522622', name: '黄平县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522623', name: '施秉县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522624', name: '三穗县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522625', name: '镇远县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522626', name: '岑巩县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522627', name: '天柱县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522628', name: '锦屏县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522629', name: '剑河县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522630', name: '台江县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522631', name: '黎平县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522632', name: '榕江县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522633', name: '从江县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522634', name: '雷山县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522635', name: '麻江县', province: '贵州省', type: 'county', parent: '黔东南州' },
      { code: '522636', name: '丹寨县', province: '贵州省', type: 'county', parent: '黔东南州' },
      
      // 黔南州
      { code: '522700', name: '黔南', province: '贵州省', type: 'prefecture' },
      { code: '522701', name: '都匀市', province: '贵州省', type: 'city', parent: '黔南州' },
      { code: '522702', name: '福泉市', province: '贵州省', type: 'city', parent: '黔南州' },
      { code: '522722', name: '荔波县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522723', name: '贵定县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522725', name: '瓮安县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522726', name: '独山县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522727', name: '平塘县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522728', name: '罗甸县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522729', name: '长顺县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522730', name: '龙里县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522731', name: '惠水县', province: '贵州省', type: 'county', parent: '黔南州' },
      { code: '522732', name: '三都县', province: '贵州省', type: 'county', parent: '黔南州' },
      
      // 新设区域
      // 贵安新区（国家级新区）
      { code: '520900', name: '贵安新区', province: '贵州省', type: 'newarea' },
      { code: '520901', name: '贵安新区直管区', province: '贵州省', type: 'district', parent: '贵安新区' }
    ]

    // 根据关键词搜索贵州城市
    const filteredCities = guizhouCities.filter(city => 
      city.name.includes(keyword) || 
      city.province.includes(keyword) ||
      (city.parent && city.parent.includes(keyword))
    )

    return {
      success: true,
      data: filteredCities
    }
  } catch (error) {
    console.error('搜索城市失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 